package org.jeecg.modules.mes.storage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.mes.client.SystemClient;
import org.jeecg.modules.mes.storage.entity.MesStockManage;
import org.jeecg.modules.mes.storage.service.IMesStockManageService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 仓库管理-库存管理
 * @Author: jeecg-boot
 * @Date: 2020-11-11
 * @Version: V1.0
 */
@Api(tags = "仓库管理-库存管理")
@RestController
@RequestMapping("/storage/mesStockManage")
@Slf4j
public class MesStockManageController extends JeecgController<MesStockManage, IMesStockManageService> {
    @Autowired
    private IMesStockManageService mesStockManageService;
    @Autowired
    SystemClient systemClient;

    /**
     * 分页列表查询
     *
     * @param mesStockManage
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "仓库管理-库存管理-分页列表查询")
    @ApiOperation(value = "仓库管理-库存管理-分页列表查询", notes = "仓库管理-库存管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(MesStockManage mesStockManage,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<MesStockManage> queryWrapper = QueryGenerator.initQueryWrapper(mesStockManage, req.getParameterMap());
        Page<MesStockManage> page = new Page<MesStockManage>(pageNo, pageSize);
        IPage<MesStockManage> pageList = mesStockManageService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param mesStockManage
     * @return
     */
    @AutoLog(value = "仓库管理-库存管理-添加")
    @ApiOperation(value = "仓库管理-库存管理-添加", notes = "仓库管理-库存管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MesStockManage mesStockManage) {
        if (StringUtils.isNotBlank(mesStockManage.getMaterielCode())) {
            String mCode = mesStockManage.getMaterielCode();
            QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("materiel_code", mCode);
            MesStockManage stockManage = mesStockManageService.getOne(queryWrapper);
            if (stockManage != null) {
                return Result.error("已存在该库存数据！请检查！");
            }
        }
        if (StringUtils.isBlank(mesStockManage.getMinimum())) {
            mesStockManage.setMinimum("0");
        }
        mesStockManageService.save(mesStockManage);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mesStockManage
     * @return
     */
    @AutoLog(value = "仓库管理-库存管理-编辑")
    @ApiOperation(value = "仓库管理-库存管理-编辑", notes = "仓库管理-库存管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MesStockManage mesStockManage) {
        mesStockManageService.updateById(mesStockManage);
        return Result.ok("编辑成功!");
    }

    @PutMapping(value = "/stockEdit")
    public String stockEdit(@RequestBody MesStockManage mesStockManage) {
        mesStockManageService.updateById(mesStockManage);
        return "编辑成功!";
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "仓库管理-库存管理-通过id删除")
    @ApiOperation(value = "仓库管理-库存管理-通过id删除", notes = "仓库管理-库存管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        mesStockManageService.removeById(id);
        return Result.ok("删除成功!");
    }

    @DeleteMapping(value = "/deleteStockByorderId")
    public String deleteStockByorderId(@RequestParam(name = "orderId", required = true) String orderId) {
        QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        mesStockManageService.remove(queryWrapper);
        return "删除成功!";
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "仓库管理-库存管理-批量删除")
    @ApiOperation(value = "仓库管理-库存管理-批量删除", notes = "仓库管理-库存管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesStockManageService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "仓库管理-库存管理-通过id查询")
    @ApiOperation(value = "仓库管理-库存管理-通过id查询", notes = "仓库管理-库存管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MesStockManage mesStockManage = mesStockManageService.getById(id);
        if (mesStockManage == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(mesStockManage);
    }

    /**
     * 通过物料料号查询
     *
     * @param
     * @return
     */
    @AutoLog(value = "仓库管理-库存管理-通过物料料号查询")
    @ApiOperation(value = "仓库管理-库存管理-通过物料料号查询", notes = "仓库管理-库存管理-通过物料料号查询")
    @GetMapping(value = "/queryByMcode")
    public MesStockManage queryByMcode(@RequestParam(name = "mcode", required = true) String mcode) {
        QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("materiel_code", mcode);
        MesStockManage mesStockManage = mesStockManageService.getOne(queryWrapper);
        return mesStockManage;
    }

    /**
     * 根据物料料号和客户名称查询库存
     *
     * @param
     * @return
     */
    @AutoLog(value = "仓库管理-库存管理-根据物料料号和客户名称查询库存")
    @ApiOperation(value = "仓库管理-库存管理-根据物料料号和客户名称查询库存", notes = "仓库管理-库存管理-根据物料料号和客户名称查询库存")
    @GetMapping(value = "/queryByMcodeAndClient")
    public MesStockManage queryByMcodeAndClient(@RequestParam(name = "mCode") String mCode,
                                                @RequestParam(name = "clientName") String clientName) {
        return mesStockManageService.queryByMcodeAndClient(mCode, clientName);
    }

    /**
     * 根据物料料号，增加库存数量
     *
     * @param mcode
     * @return
     */
    @GetMapping("storage/mesStockManage/updateMcodeNum")
    public boolean updateMcodeNum(@RequestParam(name = "mcode", required = true) String mcode,
                                  @RequestParam(name = "num", required = true) String num) {
        QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("materiel_code", mcode);
        MesStockManage mesStockManage = mesStockManageService.getOne(queryWrapper);
        if (mesStockManage != null) {
            BigDecimal snum = new BigDecimal(num);
            if (StringUtils.isBlank(mesStockManage.getStockNum())) {
                mesStockManage.setStockNum("0");
            }
            BigDecimal stocknum = new BigDecimal(mesStockManage.getStockNum());
            BigDecimal stockNownum = stocknum.add(snum);
            mesStockManage.setStockNum(stockNownum.toString());
            mesStockManageService.updateById(mesStockManage);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mesStockManage
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MesStockManage mesStockManage) {
        return super.exportXls(request, mesStockManage, MesStockManage.class, "仓库管理-库存管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//
//        return super.importExcel(request, response, MesStockManage.class);
//    }
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<MesStockManage> list = ExcelImportUtil.importExcel(file.getInputStream(), MesStockManage.class, params);
                int i = 0;
                for (MesStockManage manage : list) {
                    System.err.println("料号=================================" + manage.getMaterielCode());
                    if (StringUtils.isNotBlank(manage.getMaterielCode())) {
                        String mCode = manage.getMaterielCode();
                        QueryWrapper<MesStockManage> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("materiel_code", mCode);
                        List<MesStockManage> manageList = mesStockManageService.list(queryWrapper);
                        if (manageList.size() == 0) {
                            mesStockManageService.save(manage);
                            i += 1;
                        }
                    } else {
                        return Result.error("物料料号不能为空！");
                    }
                    if (StringUtils.isBlank(manage.getMinimum())) {
                        return Result.error("库存临界点不能为空！");
                    }
                }
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + String.valueOf(i));
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

}
